import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';

interface RequestOptions extends AxiosRequestConfig {
  loading?: boolean;
  showError?: boolean;
}

interface Response<T = any> {
  code: number;
  data: T;
  message: string;
}

// Create axios instance
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
});

// Request interceptor
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

// Response interceptor
service.interceptors.response.use(
  (response: AxiosResponse<Response>) => {
    const res = response.data;
    if (res.code !== 200) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(new Error(res.message || 'Error'));
    }
    return res;
  },
  (error) => {
    console.error('Response error:', error);
    ElMessage({
      message: error.message || 'Request failed',
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

// Request method wrapper
const request = async <T = any>(
  config: RequestOptions
): Promise<Response<T>> => {
  try {
    const response = await service.request<Response<T>>(config);
    return response;
  } catch (error) {
    if (config.showError !== false) {
      console.error('Request failed:', error);
    }
    return Promise.reject(error);
  }
};

export default request;